package com.dataeco.api.facility;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;

public class PasswordService {

    private String algorithmName;
    private int hashIterations;

    private RandomNumberGenerator randomNumberGenerator;

    public PasswordService() {
        this.randomNumberGenerator = new SecureRandomNumberGenerator();
        this.algorithmName = "SHA-256";
        this.hashIterations = 2;
    }

    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }

    public String getAlgorithmName() {
        return algorithmName;
    }

    public int getHashIterations() {
        return hashIterations;
    }

    /**
     * Encrypt credentials with credentials salt
     *
     * @param credentials credentials
     * @param salt        salt
     * @return encrypted credentials
     */
    public String encryptPassword(Object credentials, String salt) {
        return new SimpleHash(algorithmName, credentials, salt, hashIterations).toHex();
    }

    /**
     * Make credentials salt
     *
     * @return generated credentials salt
     */
    public String makeSalt() {
        return randomNumberGenerator.nextBytes().toHex();
    }

}
